package cn.edu.hit.selflearning;

import cn.edu.hit.kg.SelfLearningUtil;
import org.apache.commons.math3.linear.RealVector;
import org.springframework.web.bind.annotation.*;

import net.sf.json.*;

import java.util.*;
import java.util.stream.Collectors;

//@RestController
public class SelfLearningController {
    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, value = "init/{id}", produces = "application/json;charset=UTF-8")
    public JSONArray initSamples(@PathVariable("id") long id) {
        return SelfLearningUtil.doInit(id, SelfLearningUtil.rowMap, SelfLearningUtil.columnMap, SelfLearningUtil.trainMap);
    }

    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, value = "feat/{id}", produces = "application/json;charset=UTF-8")
    public JSONArray featFeature(@PathVariable("id") long id, @RequestParam("feature") int feature) {
        double[][] result = SelfLearningUtil.feat(SelfLearningUtil.rowMap.get(id), SelfLearningUtil.columnMap.get(id), SelfLearningUtil.trainMap.get(id), feature);
        return JSONArray.fromObject(Arrays.stream(result)
                .map(arr -> Arrays.stream(arr).mapToObj(x -> "" + x).collect(Collectors.toList()))
                .collect(Collectors.toList()));
    }

    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, value = "train/{id}", produces = "application/json;charset=UTF-8")
    public JSONArray trainFeature(@PathVariable("id") long id, @RequestParam("feature") int feature, @RequestParam("reason") int reason) {
        RealVector result = SelfLearningUtil.retrain(SelfLearningUtil.rowMap.get(id), SelfLearningUtil.columnMap.get(id), SelfLearningUtil.trainMap.get(id), feature, reason);
        return JSONArray.fromObject(result.toArray());
    }

    //    private final CacheManager cacheManager = CacheManager.getInstance();
//    private ICachedObjectPool<String,String> lastReportId = cacheManager.createCachedObjectPool("Fault.lastReportId."+this.getId());

}
